import 'package:base/main.dart';
import 'package:collection/collection.dart';
import 'package:framework/core/base_view_model.dart';
import 'package:module_discover/pages/model/filter_model.dart';
import 'package:module_discover/utils/dis_cons.dart';

/// 右侧子列表数据VM
class FilterStateVM extends BaseViewModel {
  final RxList<BaseFilterItem> activeFilters = <BaseFilterItem>[].obs;

  final childCategories = <String, RxList<BaseFilterItem>>{}.obs;

  /// 给数据源赋值右侧数据 key value的形式，便于页面刷新
  void setChildCategories(String key, List<BaseFilterItem> items) {
    childCategories.putIfAbsent(key, () => RxList<BaseFilterItem>());
    childCategories[key]?.value = items;
  }

  /// 重置所有选中状态
  void resetAllSelections() {
    _resetAllCategories();
  }

  /// 条件重置所有选中状态
  void resetSelections(String parentKey, String childKey) {
    // if (childKey == "baxz") {
    //   childKey = "sfba_1";
    //   childCategories[parentKey]?.forEach((model) {
    //     if (model.key == "childKey") {
    //       model.children.forEach((model) {
    //         if (model.children.isNotEmpty) {
    //           model.children.forEach((model) {
    //             _resetItemSelection(model);
    //           });
    //         }
    //       });
    //     }
    //   });
    //   return;
    // }
    childCategories[parentKey]?.forEach((model) {
      if (model.key == childKey) {
        _resetItemSelection(model);
      }
    });
  }

  /// 核心重置逻辑
  void _resetAllCategories() {
    childCategories.forEach((categoryKey, items) {
      items.forEach(_resetItemSelection);
    });
  }

  /// 迭代式重置方法
  void _resetItemSelection(BaseFilterItem root) {
    final stack = <BaseFilterItem>[root];

    if (root.custom != null) {
      if (root.custom?.title == DisCons.CUSTOM) {
        root.custom?.value = "";
      }
    }

    while (stack.isNotEmpty) {
      final item = stack.removeLast();
      _safeResetItem(item);

      if (item.children.isNotEmpty) {
        stack.addAll(item.children);
      }
    }
  }

  /// 安全重置方法
  void _safeResetItem(BaseFilterItem item) {
    try {
      item.isSelected.value = false;
    } catch (e) {
      Log.i('重置异常: ${item.key} - ${e.toString()}');
    }
  }

  /// 特别构成 域名构成 数据重置
  void getYMGCTECategories(String key) {
    final mData = childCategories[key];
    mData?.forEach((item) {
      for (var item in item.children) {
        item.isSelected.value = false;
      }
    });
  }
}
